/**
 *    Copyright (c) 2021 WANGFEIHU
 *    SSO-PLUS is licensed under Mulan PSL v2.
 *    You can use this software according to the terms and conditions of the Mulan PSL v2.
 *    You may obtain a copy of Mulan PSL v2 at:
 *             http://license.coscl.org.cn/MulanPSL2
 *    THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *    See the Mulan PSL v2 for more details.
 */
package cn.codinglives.ssoplus.controller;

import cn.codinglives.ssoplus.entity.SsoMain;
import cn.codinglives.ssoplus.jwt.TokenUser;
import cn.codinglives.ssoplus.saml.CurrentUser;
import cn.codinglives.ssoplus.saml.SamlUser;
import cn.codinglives.ssoplus.service.JwtService;
import cn.codinglives.ssoplus.service.SsoMainService;
import cn.codinglives.ssoplus.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@Controller
public class DispatcherController {
	
	private static final Logger LOG = LoggerFactory
			.getLogger(DispatcherController.class);

	@Resource
	private UserService userService;

	@Resource
	private SsoMainService ssoConfService;

	@Resource
	private JwtService jwtService;



	@RequestMapping("/saml2/dispatch")
	public ResponseEntity dispatch(@RequestParam(required = false) String tenantCode, @CurrentUser SamlUser user) {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (auth != null && user != null) {
			LOG.info("sso.user:{}", user.toString());
			String authTenantCode = user.getTenantCode();
			if (StringUtils.isNotBlank(tenantCode) && !tenantCode.equals(authTenantCode)) {
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("tenant code 必须一致.");
			}
			TokenUser tokenUser = null;
			try {
				tokenUser = userService.getUserInfo("");
				String accessToken = jwtService.createToken(tokenUser.getUserId());
				String url = "";
				List<SsoMain> ssoConfList = ssoConfService.list("");
				for (SsoMain conf : ssoConfList) {
					if (authTenantCode.equalsIgnoreCase(conf.getTenantCode())) {
						url = conf.getSsoUrl();
						break;
					}
				}
				url = url  + "?token=" + accessToken;
				return ResponseEntity.status(HttpStatus.FOUND).location(URI.create(url)).build();
			} catch (Exception e) {
				LOG.error("get user info error!", e);
			}
			return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("用户信息未同步!");
		} else {
			return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("用户未登录!");
		}

	}

}
